package com.qef.com.mmovie;

import android.app.Activity;
import android.app.Application;

import com.avos.avoscloud.AVOSCloud;
import com.qef.com.mmovie.di.component.AppComponent;
import com.qef.com.mmovie.di.component.DaggerAppComponent;
import com.qef.com.mmovie.di.module.AppModule;
import com.qef.com.mmovie.di.module.RetrofitModule;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 2016 逛街购（北京）网络科技有限公司，版权所有
 * guangjiegou - Android客户端
 * Context:
 * Created by fanenqian on 2017/3/20 16:11
 */
public class App extends Application {
    private AppComponent appComponent;
    private static App app;
    private Set<Activity> allActivities;
    private static ExecutorService mExecutorService;
    private static int MAX_THREAD_NUM = 5;
    @Override
    public void onCreate() {
        super.onCreate();
        app = this;
        initAppComponent();
        // 初始化参数依次为 this, AppId, AppKey  leancloud
        AVOSCloud.initialize(this, "HN9iK2m4yskGOt35X8ByXEi5-gzGzoHsz", "NzNtFCvRMgYtSdLvxgJgXwvJ");
        // 放在 SDK 初始化语句 AVOSCloud.initialize() 后面，只需要调用一次即可
        AVOSCloud.setDebugLogEnabled(true);
    }

    private void initAppComponent() {
        appComponent = DaggerAppComponent.builder().appModule(new AppModule(this)).retrofitModule(new RetrofitModule(this)).build();
    }

    public AppComponent getAppComponent() {
        return appComponent;
    }

    public static App getInstance() {
        return app;
    }

    public void addActivity(Activity act) {
        if (allActivities == null) {
            allActivities = new HashSet<>();
        }
        allActivities.add(act);
    }

    public void removeActivity(Activity act) {
        if (allActivities != null) {
            allActivities.remove(act);
        }
    }

    public void exitApp() {
        if (allActivities != null) {
            synchronized (allActivities) {
                for (Activity act : allActivities) {
                    act.finish();
                }
            }
        }
        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(0);
    }
    /**
     * The thread pool objects, at most five threads
     *
     * @return
     */
    public static ExecutorService getThreadPool() {
        if (mExecutorService == null) {
            mExecutorService = Executors.newFixedThreadPool(MAX_THREAD_NUM);
        }
        return mExecutorService;
    }

}
